import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/pages/ali_player/short_video/short_video_page.dart';

import 'index.dart';

class FavoriteListPage extends GetView<FavoriteListController> {
  const FavoriteListPage({Key? key}) : super(key: key);

  // 视频项组件
  Widget _buildVideoItem(VideoModel video) {
    return GestureDetector(
      onTap: () => jumpTo_ShortVideoPage(video),
      child: Card(
        color: Colors.black,
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                // 视频封面图
                AspectRatio(
                  aspectRatio: 11 / 13, // 固定宽高比
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(8),
                    ),
                    child: CachedNetworkImage(
                      imageUrl: video.imgUrl!,
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) => Icon(Icons.error),
                    ),
                  ),
                ),
                // 底部居中的标签 - Episode 5/50
                // 底部居中的标签 - Episode 5/50 带灰色半透明弧形背景
                Positioned(
                  // 标签位置：底部居中，带一点底边距
                  bottom: 5, // 距离底部8px
                  left: 0, // 左侧对齐父容器
                  right: 0, // 右侧对齐父容器
                  child: Center(
                    // 文本居中显示
                    child: Container(
                      // 背景装饰
                      decoration: BoxDecoration(
                        color: const Color(
                          0xFF000000,
                          // ignore: deprecated_member_use
                        ).withOpacity(0.7), // 灰色半透明背景
                        borderRadius: BorderRadius.circular(10), // 弧形边角
                      ),
                      // 内边距，让文字与背景边缘有一定距离
                      padding: const EdgeInsets.symmetric(
                        horizontal: 5,
                        vertical: 2,
                      ),
                      // child: Center(
                      child: Text(
                        "Episode ${video.sortId}/${video.videoNum} ",
                        style: TextStyle(
                          color: const Color(0xFFFFFFFF), // 文字颜色#FFFFFF
                          fontSize: 9, // 9pt转换为sp
                          shadows: [
                            Shadow(
                              color: const Color(
                                0xFF756966,
                                // ignore: deprecated_member_use
                              ).withOpacity(0.5), // 阴影颜色#756966 50%
                              offset: const Offset(0, 1),
                              blurRadius: 2,
                            ),
                          ],
                        ),
                      ),
                      // ),
                    ),
                  ),
                ),
              ],
            ),

            // 视频标题
            Padding(
              padding: const EdgeInsets.all(8),
              child: Text(
                video.name!,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 11,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 网格布局
  Widget _buildGridView() {
    // return GetX<FavoriteListController>(
    //   builder: (controller) {
    return AlignedGridView.count(
      crossAxisCount: 3, // 2列布局
      mainAxisSpacing: 10, // 纵向间距
      crossAxisSpacing: 10, // 横向间距
      padding: const EdgeInsets.all(10),
      itemCount: controller.state.videoList.length,
      itemBuilder: (context, index) {
        return _buildVideoItem(controller.state.videoList[index]);
      },
      // 所有项具有相同的高度
    );
    //   },
    // );
  }

  // 主视图
  Widget _buildView() {
    return Obx(() {
      return SmartRefresher(
        controller: controller.refreshController,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: controller.onRefresh,
        onLoading: controller.onLoading,
        child: controller.state.isNeedShowEmpty.value
            ? _buildEmptyState()
            : _buildGridView(),
      );
    });
  }

  // 空状态视图
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 空数据图片（这里使用网络图片示例，实际项目中建议使用本地资源图片）
          Image.asset(
            'assets/images/empty.png', // 本地未选中状态图片路径
            width: 150,
            height: 150,
            fit: BoxFit.contain,
          ),
          const SizedBox(height: 20),
          // Text(
          //   "暂无消费记录".tr,
          //   style: const TextStyle(fontSize: 16, color: Color(0xFF999999)),
          // ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    String collectionText = '我的收藏'.tr;

    return Scaffold(
      appBar: AppBar(
        // '我的收藏'
        title: Text(collectionText, style: TextStyle(color: Colors.white)),
        // 自定义返回按钮
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white), // 强制白色
          onPressed: () => Navigator.of(context).pop(), // 返回上一页
        ),
        // backgroundColor: Colors.blue, // 确保与白色文字有对比
      ),
      body: SafeArea(child: _buildView()),
    );
  }

  jumpTo_ShortVideoPage(dynamic mode) {
    // 跳转时保留原页面在路由栈中
    Get.to(
      () =>
          ShortVideoPage(preload: false, isforyouPage: false, superModel: mode),
    )?.then((result) {
      final currentCtl = Get.find<FavoriteListController>();
      // 先手动触发刷新动画
      currentCtl.refreshController.requestRefresh();
      // 再执行刷新逻辑
      currentCtl.onRefresh();
    });
  }
}
